﻿using System;
using System.Collections.Generic;
using Contracts.Entities;
using Contracts.Library;
using Model.Movie;
using NLog;

namespace Definition.Import
{
    public class ImportMoviesService 
    {
        protected Logger logger = LogManager.GetCurrentClassLogger();

        private ReadMovieItemsFromDirectory directoryReader;
        private WriteMovieItems dbWriter;
        private ReadMovieItemsLookup dbReader;
        private SynchronizeMovieItems synchronizer;

        public ImportMoviesService()
        {
            this.directoryReader = new ReadMovieItemsFromDirectory();
            this.dbWriter = new WriteMovieItems();
            this.dbReader = new ReadMovieItemsLookup();
            this.synchronizer = new SynchronizeMovieItems();

            //Bind      
            var join = new Join<IEnumerable<MovieItem>, IEnumerable<MovieItem>>();

            directoryReader.OnCompleted += join.InputA;
            dbReader.OnCompleted += join.InputB;
            join.OnCompleted += synchronizer.Process;
            synchronizer.OnCompleted += dbWriter.Process;
            synchronizer.OnCompleted += (m) => OnCompleted(m);
        }

        public void Process(string directoryPath)
        {
            try
            {
                logger.Debug("Try import movies from local directory");

                directoryReader.Process(directoryPath);
                dbReader.Process();
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
        }

        public event Action<IEnumerable<MovieItem>> OnCompleted;
    }
}
